import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Modal, Form, Space, Switch, message, Popconfirm } from 'antd';
import { PlusOutlined, SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import axios from 'axios';

interface UserData {
  key: number;
  id: number;
  name: string;
  username: string;
  status: string;
  email: string;
  role: string;
  createTime: string;
}

const UserManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [dataSource, setDataSource] = useState<UserData[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<UserData | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const fetchUsers = async (params: any = {}) => {
    setLoading(true);
    try {
      const response = await axios.post('/api/system/users', params);
      if (response.data.code === 200) {
        const users = response.data.data.map((item: any) => ({
          key: item.key,
          id: item.key,
          name: item.name,
          username: item.user,
          status: item.status,
          email: item.email,
          role: '普通用户',
          createTime: item.time,
        }));
        setDataSource(users);
        setPagination({
          ...pagination,
          total: response.data.data.length,
        });
      }
    } catch (error) {
      console.error('获取用户列表失败', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    fetchUsers(values);
  };

  const handleAdd = () => {
    form.resetFields();
    setEditingUser(null);
    setModalVisible(true);
  };

  const handleEdit = (record: UserData) => {
    setEditingUser(record);
    form.setFieldsValue({
      name: record.name,
      username: record.username,
      email: record.email,
      status: record.status === 'running',
      role: record.role,
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      // 在实际项目中替换为实际的删除API调用
      // await axios.delete(`/api/system/users/${id}`);
      setDataSource(dataSource.filter(item => item.id !== id));
      message.success('删除成功');
    } catch (error) {
      console.error('删除用户失败', error);
      message.error('删除用户失败');
    }
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingUser) {
        // 更新用户
        const updatedData = dataSource.map(item => {
          if (item.id === editingUser.id) {
            return {
              ...item,
              name: values.name,
              username: values.username,
              email: values.email,
              status: values.status ? 'running' : 'stop',
              role: values.role,
            };
          }
          return item;
        });
        setDataSource(updatedData);
        message.success('更新用户成功');
      } else {
        // 添加用户
        const newUser: UserData = {
          key: Date.now(),
          id: Date.now(),
          name: values.name,
          username: values.username,
          email: values.email,
          status: values.status ? 'running' : 'stop',
          role: values.role,
          createTime: new Date().toLocaleString(),
        };
        setDataSource([...dataSource, newUser]);
        message.success('添加用户成功');
      }
      
      setModalVisible(false);
    } catch (error) {
      console.error('表单验证失败', error);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <span className={status === 'running' ? 'text-green-500' : 'text-red-500'}>
          {status === 'running' ? '启用' : '停用'}
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: UserData) => (
        <Space size="middle">
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此用户吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="bg-white p-6 rounded-lg shadow">
      <div className="mb-4">
        <Form form={searchForm} layout="inline">
          <Form.Item name="name" label="姓名">
            <Input placeholder="请输入姓名" allowClear />
          </Form.Item>
          <Form.Item name="username" label="用户名">
            <Input placeholder="请输入用户名" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      
      <div className="mb-4">
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新增用户
        </Button>
      </div>
      
      <Table
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        pagination={pagination}
        rowKey="id"
      />

      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => setModalVisible(false)}
        maskClosable={false}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          {!editingUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
            initialValue="普通用户"
          >
            <Input placeholder="请选择角色" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
            initialValue={true}
          >
            <Switch checkedChildren="启用" unCheckedChildren="停用" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement; 
